package com.fanhang.samples.spring.session.controller;

import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping
public class LoginController {

	private final Map<String, String> users = new HashMap<String, String>(){{
		put("a", "a");
		put("b", "b");
		put("c", "c");
	}};

	/**
	 * 显示登录页
	 * 
	 * @param rq
	 * @return
	 */
	@RequestMapping(value = { "/login" }, method = { RequestMethod.GET })
	public Object login(HttpSession session, @RequestParam("user") String user, @RequestParam("pwd") String pwd) {
		String password = users.get(user);
		if (password == null) {
			return "用户名不存在";
		}
		if (!password.equals(pwd)) {
			return "用户名/密码错误";
		}
		session.setAttribute(user, pwd);
		return "登录成功";
	}

	/**
	 * 退出处理
	 * 
	 * @param rq
	 * @param resp
	 * @return
	 */
	@RequestMapping(value = { "/logout" }, method = { RequestMethod.GET })
	public Object logout(HttpSession session, @RequestParam("user") String user) {
		session.removeAttribute(user);
		return session.getAttribute(user);
	}
}